package com.qyhl.webtv.module_news.news.smallvideo.homelist;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.CatchSmallBean;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.video.normalvideo.QYVideoPlayer2;
import com.qyhl.webtv.module_news.utils.RecyclerViewScrollUtil;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.socialize.UMShareAPI;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/4/24.
 *
 * @author qyhl
 */

@Route(path = ARouterPathConstant.SMALL_VIDEO_LIST)
public class SmallVideoListActivity extends BaseActivity implements SmallVideoListContract.SmallVideoListView {
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.next)
    TextView next;


    private RecyclerViewScrollUtil scrollUtil;

    private HeaderAndFooterWrapper headerAndFooterWrapper;

    private CommonAdapter commonAdapter;

    private GlobalNewsBean newsBean;

    private List<CatchSmallBean.NewsDetail> mDataList;

    private SmallVideoListPresenter mPresenter;

    /**
     * 定时器
     */
    protected Timer processTimer;

    //定时器任务
    protected ProgressTimerTask mProgressTimerTask;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT > 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

    }


    @Override
    protected int getContentView() {
        return R.layout.news_activity_smallvideo_list;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        setSupportActionBar(toolbar);
        mPresenter = new SmallVideoListPresenter(this);
        newsBean = (GlobalNewsBean) getIntent().getSerializableExtra("bean");
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getVideoList(newsBean.getNewsId());
    }

    /**
     * 初始化
     */
    private void initView() {
        mDataList = new ArrayList<>();
        if (newsBean != null) {
            CatchSmallBean.NewsDetail firstBean = new CatchSmallBean.NewsDetail(Integer.parseInt(newsBean.getNewsId()), newsBean.getCover(), Integer.parseInt(newsBean.getCatalogId()), newsBean.getTitle(), newsBean.getUrl(), newsBean.getScanNum());
            mDataList.add(firstBean);
        }

        //设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recycleView.setLayoutManager(layoutManager);

        commonAdapter = new CommonAdapter<CatchSmallBean.NewsDetail>(this, R.layout.news_item_home_small_video_list, mDataList) {

            @Override
            protected void convert(ViewHolder holder, final CatchSmallBean.NewsDetail bean, final int position) {
                //标题
                TextView title = holder.getView(R.id.title);
                title.setText(bean.getTitle());

                //蒙层
                View mask = holder.getView(R.id.mask);

                //评论数
                TextView commentNum = holder.getView(R.id.comment);
                commentNum.setText(bean.getClickCount() > 0 ? bean.getClickCount() + "" : "评论");

                commentNum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("newsId", bean.getId() + "");
                        RouterManager.router(ARouterPathConstant.SMALL_VIDEO_DETAIL_ACTIVITY,bundle);

                    }
                });

                //分享
                TextView share = holder.getView(R.id.share);

                share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MPermissionUtils.requestPermissionsResult(SmallVideoListActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                            @Override
                            public void onPermissionGranted() {
                                MShareBoard shareBoard = new MShareBoard(SmallVideoListActivity.this, bean.getId() + "", bean.getTitle(), bean.getCover(),"" , 4, true);
                                shareBoard.showPopupWindow();
                            }

                            @Override
                            public void onPermissionDenied() {
                                MPermissionUtils.showTipsDialog(SmallVideoListActivity.this);
                            }
                        });
                    }
                });


                //设置父栏目标志
                TextView type = holder.getView(R.id.type);
                final int mIndex;
                switch (bean.getSectionId()) {
                    case 1000006:
                            type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(SmallVideoListActivity.this, R.drawable.small_video_tag_laugh), null, null, null);
                        type.setText("搞笑");
                        mIndex = 1;
                        break;
                    case 1000007:
                        type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(SmallVideoListActivity.this, R.drawable.small_video_tag_cute), null, null, null);
                        type.setText("萌物");
                        mIndex = 2;
                        break;
                    case 1000008:
                        type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(SmallVideoListActivity.this, R.drawable.small_video_tag_sport), null, null, null);
                        type.setText("运动");
                        mIndex = 3;
                        break;
                    case 1000009:
                        type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(SmallVideoListActivity.this, R.drawable.small_video_tag_entertainment), null, null, null);
                        type.setText("娱乐");
                        mIndex = 4;
                        break;
                    case 10000010:
                        type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(SmallVideoListActivity.this, R.drawable.small_video_tag_live), null, null, null);
                        type.setText("现场");
                        mIndex = 5;
                        break;
                    default:
                        type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(SmallVideoListActivity.this, R.drawable.small_video_tag_home), null, null, null);
                        type.setText("精选");
                        mIndex = 0;
                        break;
                }


                final QYVideoPlayer2 videoPlayer = holder.getView(R.id.video_player);
                ImageView imageView = new ImageView(SmallVideoListActivity.this);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                Glide.with(SmallVideoListActivity.this)
                        .load(bean.getCover())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_video_default).error(R.drawable.cover_video_default))
                        .into(imageView);

                videoPlayer.setThumbImageView(imageView);

                videoPlayer.getBackButton().setVisibility(View.GONE);
                videoPlayer.setRotateViewAuto(false);
                videoPlayer.setLockLand(true);
                videoPlayer.setUp(bean.getUrl() == null ? "" : bean.getUrl(), true, " ");
                videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        videoPlayer.startWindowFullscreen(SmallVideoListActivity.this, true, true);
                    }
                });

                videoPlayer.setVideoListListener(new QYVideoPlayer2.VideoListListener() {
                    @Override
                    public void completion() {
                        next.setVisibility(View.GONE);
                        if (position != (mDataList.size() - 2) && position != (mDataList.size() - 1)) {
                            scrollUtil.checkPosition(position + 1);
                        }
                    }

                    @Override
                    public void afterStart() {
                        mPresenter.count(bean.getId() + "");
                    }
                });

                if (position == 1) {
                    mask.setVisibility(View.GONE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            scrollUtil.checkPosition(1);
                            videoPlayer.startPlayLogic();
                        }
                    }, 300);
                } else {
                    mask.setVisibility(View.VISIBLE);
                }

                mask.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        scrollUtil.checkPosition(position);
                    }
                });

                /**
                 * 类型
                 */
                type.setOnClickListener(v -> {

                    Bundle bundle= new Bundle();
                    bundle.putString("index", mIndex+"");
                    RouterManager.router(ARouterPathConstant.SMALLVIDEO,bundle);

                    videoPlayer.release();

                });


            }
        };


        headerAndFooterWrapper = new HeaderAndFooterWrapper(commonAdapter);

        View headerView = LayoutInflater.from(this).inflate(R.layout.news_item_video_list_index_view, null);
        View footerView = LayoutInflater.from(this).inflate(R.layout.news_item_video_list_index_view, null);

        if (headerView != null) {
            headerAndFooterWrapper.addHeaderView(headerView);
        }

        if (footerView != null) {
            headerAndFooterWrapper.addFootView(footerView);
        }

        recycleView.setAdapter(headerAndFooterWrapper);

        scrollUtil = new RecyclerViewScrollUtil(recycleView);
        scrollUtil.setType(RecyclerViewScrollUtil.TYPE_CENTER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        next.setVisibility(View.GONE);
        scrollUtil.setListener(new RecyclerViewScrollUtil.ScrollListener() {
            @Override
            public void change(int position) {
                if (position != 0 && position != (headerAndFooterWrapper.getItemCount() - 1)) {
                    for (int i = 1; i < headerAndFooterWrapper.getItemCount() - 1; i++) {
                        ViewHolder holder = (ViewHolder) recycleView.findViewHolderForAdapterPosition(i);
                        if (holder != null) {
                            View mask = holder.getView(R.id.mask);
                            QYVideoPlayer2 videoPlayer = holder.getView(R.id.video_player);
                            if (i == position) {
                                mask.setVisibility(View.GONE);
                                videoPlayer.startPlayLogic();
                                startProgressTimer(videoPlayer);
                            } else {
                                mask.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                } else if (position == 0) {
                    ViewHolder holder = (ViewHolder) recycleView.findViewHolderForAdapterPosition(1);
                    ViewHolder holder2 = (ViewHolder) recycleView.findViewHolderForAdapterPosition(2);
                    if (holder != null) {
                        QYVideoPlayer2 videoPlayer = holder.getView(R.id.video_player);
                        startProgressTimer(videoPlayer);
                        View mask = holder.getView(R.id.mask);
                        mask.setVisibility(View.GONE);
                        videoPlayer.startPlayLogic();
                    }
                    if (holder2 != null) {
                        View mask = holder2.getView(R.id.mask);
                        mask.setVisibility(View.VISIBLE);
                    }
                } else {
                    ViewHolder holder = (ViewHolder) recycleView.findViewHolderForAdapterPosition(headerAndFooterWrapper.getItemCount() - 2);
                    ViewHolder holder2 = (ViewHolder) recycleView.findViewHolderForAdapterPosition(headerAndFooterWrapper.getItemCount() - 3);
                    if (holder != null) {
                        QYVideoPlayer2 videoPlayer = holder.getView(R.id.video_player);
                        startProgressTimer(videoPlayer);
                        View mask = holder.getView(R.id.mask);
                        mask.setVisibility(View.GONE);
                        videoPlayer.startPlayLogic();
                    }
                    if (holder2 != null) {
                        View mask = holder2.getView(R.id.mask);
                        mask.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void stopSrcoll(int position) {
                ViewHolder holder = (ViewHolder) recycleView.findViewHolderForAdapterPosition(position);
                if (holder != null) {
                    QYVideoPlayer2 videoPlayer = holder.getView(R.id.video_player);
                    videoPlayer.dismissDialog();
                }
            }


        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                scrollUtil.checkPosition(position);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void setVideoList(List<CatchSmallBean.NewsDetail> beanList) {
        if (beanList != null) {
            mDataList.addAll(beanList);
        }
        headerAndFooterWrapper.notifyDataSetChanged();

    }

    @Override
    public void setError(String msg) {
        Toasty.normal(this, "暂无更多视频").show();
        headerAndFooterWrapper.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        cancelProgressTimer();
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void startProgressTimer(QYVideoPlayer2 videoPlayer) {
        cancelProgressTimer();
        processTimer = new Timer();
        mProgressTimerTask = new ProgressTimerTask(videoPlayer);
        processTimer.schedule(mProgressTimerTask, 1000, 1000);
    }

    private class ProgressTimerTask extends TimerTask {
        QYVideoPlayer2 videoPlayer;

        public ProgressTimerTask(QYVideoPlayer2 videoPlayer) {
            this.videoPlayer = videoPlayer;
        }

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (videoPlayer.getDuration() != 0 && (videoPlayer.getDuration() - videoPlayer.getCurrentPositionWhenPlaying()) / 1000 <= 3) {
                        if (next != null) {
                            next.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

        }
    }

    protected void cancelProgressTimer() {
        if (processTimer != null) {
            processTimer.cancel();
            processTimer = null;
        }
        if (mProgressTimerTask != null) {
            mProgressTimerTask.cancel();
            mProgressTimerTask = null;
        }

    }


    @Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(SmallVideoListActivity.this)) {
            return;
        }
        super.onBackPressed();
    }


}
